//
//  RAPEmoticonKeyboardViewModel.swift
//  COPYCAT-Weibo
//
//  Created by 闫萌 on 1/7/16.
//  Copyright © 2016 RendezvousAuParadis. All rights reserved.
//

import UIKit

private let kSectionCapacity = 20

class RAPEmoticonKeyboardViewModel: NSObject {
    // MARK: - 单例方法
    static let sharedViewModel: RAPEmoticonKeyboardViewModel = {
        let sharedViewModel = RAPEmoticonKeyboardViewModel()
        return sharedViewModel
    }()
    
    private let recentEmoticonsFilePath: String = {
        let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first
        return (path! as NSString).stringByAppendingPathComponent("recentEmoticons")
    }()
    
    // MARK: - 自定义属性
    /// 三维数组
    lazy var tripleDArray: [[[RAPEmoticonModel]]] = [
        self.recentEmoticons,
        self.defaultEmoticon,
        self.emojiEmoticon,
        self.lxhEmoticon
    ]
    
    /// 表情bundle
    lazy var emoticonBundle: NSBundle = {
        let path = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)
        let emoticonBundle = NSBundle(path: path!)
        return emoticonBundle!
    }()
    
    
    ///  向最近表情数组添加表情
    ///
    ///  - parameter model: 需要添加的表情
    func addRecentEmoticon(model: RAPEmoticonModel) {
        
        /*
        操你妹，swift中集合都是值类型，根本不是对象，赋值是复制而非引用传递，草
        */
        let tmpArr = (recentEmoticons[0] as NSArray).mutableCopy() as! NSMutableArray
        /*
        先删除，再添加
        */
        let idxArr = NSMutableIndexSet()
        tmpArr.enumerateObjectsWithOptions([]) { (inModel, idx, _) -> Void in
            if (inModel as! RAPEmoticonModel).isEqual(model) {
                RAPLog("有重复")
                idxArr.addIndex(idx) // 保存出一个从前后的顺序
            }
        }
        
        tmpArr.removeObjectsAtIndexes(idxArr)

        tmpArr.insertObject(model, atIndex: 0)
        
        while tmpArr.count > 20 {
            tmpArr.removeLastObject()
        }
        
        recentEmoticons[0] = tmpArr.copy() as! Array<RAPEmoticonModel>
        // 数组是值类型，所以要重新赋值
        tripleDArray[0] = recentEmoticons
        
        // 归档
        writeRecentEmoticons()
    }
    
    
    
    // MARK: - 懒加载属性
    /*
    通过定义懒加载属性，使得三种表情只加载一次
    */
    lazy var recentEmoticons: [[RAPEmoticonModel]] = {
        
        if let opRecentEmoticons = self.readRecentEmoticons() {
            return opRecentEmoticons
        }

        return [[RAPEmoticonModel]()]
    }()
    
    private lazy var defaultEmoticon: [[RAPEmoticonModel]] = {
        return self.wrapModelsIntoNestedArrayByPath("default/info.plist")
        }()
    
    private lazy var emojiEmoticon: [[RAPEmoticonModel]] = {
        return self.wrapModelsIntoNestedArrayByPath("emoji/info.plist")
        }()
    
    private lazy var lxhEmoticon: [[RAPEmoticonModel]] = {
        return self.wrapModelsIntoNestedArrayByPath("lxh/info.plist")
        }()
    
    ///  从包中读取info.plist文件，将其中转换为模型数组，并打散位若干个一级数组，打包返回
    ///  20个表情一组，一级数组
    ///
    ///  - parameter bundle: 包
    ///  - parameter path:   info.plist在包中的路径
    ///
    ///  - returns: 包含若干个一级数组的二级数组
    private func wrapModelsIntoNestedArrayByPath(path: String) -> [[RAPEmoticonModel]] {
        // 表情info.plist的路径
        let rawPath = emoticonBundle.pathForResource(path, ofType: nil)
        // 从bundle中读取的原始表情数组
        let rawArr = NSArray(contentsOfFile: rawPath!)

        // 存放转换后的模型的临时素组
        var tmpArr = [RAPEmoticonModel]()
        
        var pathComponent = ""
        if path.rangeOfString("default") != nil { // 默认
            pathComponent = "default/"
        } else if path.rangeOfString("emoji") != nil { // emoji
            pathComponent = "emoji/"
        } else if path.rangeOfString("lxh") != nil {
            pathComponent = "lxh/"
        } else {
            RAPLog("漏网之鱼")
        }
        
        for dict in rawArr! { // 字典转模型
            let model = RAPEmoticonModel(dict: dict as! [String : AnyObject])
            
            if let opPng = model.png {
                model.png = pathComponent + opPng
            }
            
            tmpArr.append(model)
        }
        
        // 将临时数组打散位若干个一级数组，并打包返回
        return breakDownArray(tmpArr)
        
    }
    
    ///  将原始数组打散，20个一组装入二级数组
    ///
    ///  - parameter wholeArray: 原始数组
    ///
    ///  - returns: 二级数组
    private func breakDownArray(wholeArray: [RAPEmoticonModel]) -> [[RAPEmoticonModel]] {
        // 分页页数
        let pages = (wholeArray.count - 1) / kSectionCapacity + 1
        
        var length = 0
        // 每次开始截取的起始位置
        var location = 0
        var superArr = [[RAPEmoticonModel]]()
        
        for i in 0..<pages {
            location = i * length
            length = (i == pages - 1) ? (wholeArray.count - i * kSectionCapacity) : kSectionCapacity
            let subArr = (wholeArray as NSArray).subarrayWithRange(NSMakeRange(location, length)) as! [RAPEmoticonModel]
            superArr.append(subArr)
        }
        
        return superArr
    }
    
}

// MARK: - 归档/解当最近表情数组
extension RAPEmoticonKeyboardViewModel {
    
    func writeRecentEmoticons() {
        NSKeyedArchiver.archiveRootObject(recentEmoticons, toFile: recentEmoticonsFilePath)
    }
    
    func readRecentEmoticons() -> [[RAPEmoticonModel]]? {
        return NSKeyedUnarchiver.unarchiveObjectWithFile(recentEmoticonsFilePath) as? [[RAPEmoticonModel]]
    }

}
